package com.mingtu.guards.activity;

import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import androidx.drawerlayout.widget.DrawerLayout;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlay;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AirBaseInfoBean;
import com.mingtu.guards.bean.AirLastLocationBean;
import com.mingtu.guards.callback.MyStringDialogCallback;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.view.CommonMapView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AircraftMapActivity extends MyBaseActivity {
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    @BindView(R.id.status_bar_view)
    View statusBarView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_list_mode)
    ImageView ivListMode;
    @BindView(R.id.layout_drawer)
    DrawerLayout layoutDrawer;
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private TileOverlay tileOverlay;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;
    private int airStatus = 0;
    private Timer timer = new Timer();
    private boolean isPause = false;
    private Handler mHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (!isPause) getAirBaseInfo();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    /**
     * 定义并初始化定时器任务
     */
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            /**
             * 此处执行任务
             * */
            mHanlder.sendEmptyMessage(1);//通知UI更新
        }
    };
    private CommonMapView commonMapView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_equi_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();
        ivListMode.setVisibility(View.GONE);
        layoutDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        commonMapView = findViewById(R.id.common_map_view);
        commonMapView.setMapParam(savedInstanceState);
        aMap = commonMapView.getAMap();
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                startTimer();
            }
        });
        //自定义瓦片
        tileOverlay = commonMapView.getTileOverlay();
    }

    @OnClick({R.id.iv_switch, R.id.iv_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        isPause = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isPause = true;
    }

    @Override
    protected void onDestroy() {
        if (markerList.size() > 0) {
            markerList.clear();
        }

        //自定义瓦片
        if (tileOverlay != null) {
            tileOverlay.setVisible(false);
            tileOverlay.remove();
        }
        stopTimer();
        super.onDestroy();

    }

    /**
     * 开始循环请求
     */
    private void startTimer() {
        timer.schedule(timerTask,
                0 * 1000,//延迟0秒执行
                1500);//周期为1秒
    }

    /**
     * 结束循环请求
     */
    private void stopTimer() {

        isPause = true; //是否暂停循环请求
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    /**
     * 获取无人机相关信息
     */
    private void getAirBaseInfo() {
        OkGo.<String>post(MyConstant.POST_AIR_BASEINFO)
                .tag(this)
                .upJson("")
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AirBaseInfoBean airBaseInfoBean = new AirBaseInfoBean();
                                airBaseInfoBean = gson.fromJson(result, AirBaseInfoBean.class);

                                if (airBaseInfoBean != null) {
                                    AirBaseInfoBean.AirInfoBean airInfoBean = airBaseInfoBean.getAirInfo();
                                    if (airInfoBean != null) {
                                        String airName = airInfoBean.getName();
                                        int status = airInfoBean.getStatus(); //0:离线  1:在线
                                        String rtmpURL = airInfoBean.getRtmpUrl();
                                        airStatus = status;

                                        if (status == 0) { //离线的时候清除图标
                                            if (markerList.size() > 0) {
                                                for (Marker marker : markerList) {
                                                    marker.remove();
                                                }
                                                markerList.clear();
                                            }
                                        } else if (status == 1) {
                                            getAirLastLocation();
                                        }

                                        //防止页面退出了，方法还在执行，对象获取为空
//                                        runOnUiThread(() -> {
//                                            if (!StringUtils.isEmpty(airName) && tvAircraftName != null) {
//                                                tvAircraftName.setText(airName + "");
//                                            }
//
//                                            if (viewStatus != null) {
//                                                if (status == 0) {
//                                                    viewStatus.setBackground(getDrawable(R.drawable.shape_circle_red));
//                                                } else if (status == 1) {
//                                                    viewStatus.setBackground(getDrawable(R.drawable.shape_circle_green_ff0));
//                                                }
//                                            }
//                                        });


                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 获取无人机最新位置信息
     */
    private void getAirLastLocation() {
        OkGo.<String>post(MyConstant.POST_AIR_LAST_LOCATION)
                .tag(this)
                .upJson("")
                .execute(new MyStringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AirLastLocationBean airLastLocationBean = new AirLastLocationBean();
                                airLastLocationBean = gson.fromJson(result, AirLastLocationBean.class);
                                if (airLastLocationBean != null) {
                                    AirLastLocationBean.AirInfoEntityBean airInfoEntityBean = airLastLocationBean.getAirInfoEntity();
                                    String lnglat = airInfoEntityBean.getLnglat();

                                    if (lnglat.indexOf(",") != -1) {
                                        String[] array = lnglat.split(",");
                                        if (array.length == 2) {
                                            double lng = Double.parseDouble(array[0]);
                                            double lat = Double.parseDouble(array[1]);

                                            LatLng location = new LatLng(lat, lng);

                                            if (markerList.size() > 0) {
                                                for (Marker marker : markerList) {
                                                    marker.remove();
                                                }
                                                markerList.clear();
                                            }

                                            ApplicationInfo appInfo = getApplicationInfo();
                                            ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                                            for (int i = 1; i <= 12; i++) {
                                                int resID = getResources().getIdentifier("icon_aircraft" + i, "mipmap", appInfo.packageName);
                                                giflist.add(BitmapDescriptorFactory.fromResource(resID));
                                            }

                                            MarkerOptions markerOptions = new MarkerOptions()
                                                    .position(location)
                                                    .period(5)
                                                    .anchor(0.5f, 0.5f)
                                                    .icons(giflist);
                                            Marker marker = aMap.addMarker(markerOptions);
                                            markerList.add(marker);
                                            aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));

//                                            latLngs.add(location);
//                                            //去重
//                                            latLngs = new ArrayList<LatLng>(new LinkedHashSet(latLngs));
//                                            List<LatLng> optimizeLatLng = mpathSmoothTool.pathOptimize(latLngs);
//                                            Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
//                                                    .addAll(optimizeLatLng)
//                                                    .width(Constant.POLYLINE_WIDTH)
//                                                    .color(context.getResources().getColor(R.color.colorPrimary)));
//                                            polylinesList.add(mapPolyline);
                                        }
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}